package com.yanyu.space.common.swagger.gateway;

import com.yanyu.space.common.core.bootlog.BootstrapLogContext;
import com.yanyu.space.common.core.properties.SwaggerGatewayProperties;
import com.yanyu.space.common.swagger.gateway.handler.SwaggerEndpoint;
import com.yanyu.space.common.swagger.gateway.handler.SwaggerRouteContext;
import com.yanyu.space.common.swagger.gateway.handler.SwaggerRouteGenerate;
import com.yanyu.space.common.swagger.gateway.handler.SwaggerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.config.GatewayAutoConfiguration;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.stream.Collectors;

/**
 * @author yanyu
 */
@Configuration
@ConditionalOnClass(GatewayAutoConfiguration.class)
@ConditionalOnProperty(value = "space.swagger.gateway.locator.enabled", matchIfMissing = true)
@EnableConfigurationProperties({SwaggerGatewayProperties.class})
public class SwaggerGatewayAutoConfiguration {

    public SwaggerGatewayAutoConfiguration() {
        BootstrapLogContext.put("swagger", "开启swagger功能");
    }

    @Bean
    @ConditionalOnMissingBean(SwaggerRouteGenerate.class)
    public SwaggerRouteGenerate swaggerRouteRule() {
        return new SwaggerRouteGenerate();
    }

    @Bean
    @Primary
    public SwaggerRouteContext swaggerRouteHold(GatewayProperties gatewayProperties, SwaggerRouteGenerate swaggerRouteRule) {
        return new SwaggerRouteContext(gatewayProperties, swaggerRouteRule);
    }

    @Bean
    public DiscoveryClientSwaggerRouteLocator discoveryClientSwaggerRouteLocator(
            DiscoveryClient discoveryClient, SwaggerRouteGenerate swaggerRouteRule,
            SwaggerRouteContext swaggerRouteHold, SwaggerGatewayProperties gatewayProperties) {
        return new DiscoveryClientSwaggerRouteLocator(discoveryClient, swaggerRouteRule, swaggerRouteHold, gatewayProperties);
    }

    @Bean
    public SwaggerProvider skySwaggerProvider(SwaggerRouteContext swaggerRouteContext) {
        return new SwaggerProvider(swaggerRouteContext);
    }

    @Bean
    public SwaggerEndpoint skySwaggerEndpoint(SwaggerProvider skySwaggerProvider) {
        return new SwaggerEndpoint(skySwaggerProvider);
    }
}
